<template>
    <div class="prize-base-setting">
        <el-form class="detail-content" :model="pageData" label-width="120px">
            <!-- <el-form-item label="大屏背景图片：">
                <el-row class="vertical-top">
                    <div class="img-container">
                        <img class="bg-img" :src="pageData.bgImage" />
                        <span v-if="!pageData.bgImage">未设置背景</span>
                    </div>
                    <el-button type="text" @click="picLibraryVisibly = true">图片库</el-button>
                    <el-button type="text" @click="clearBg">清除</el-button>
                    <el-button type="danger" @click="goTpshow">高级编辑</el-button>
                </el-row>
                <div class="detail-tip">如果为空，则默认显示整体设置中的背景图片</div>
            </el-form-item> -->
          <backgComponent @change="bgChange" :key="pageData.d3Config" :bgdata.sync="pageData.d3Config">
            <el-button slot="right" style="margin-left:10px" type="danger" @click="goTpshow">高级编辑</el-button>
          </backgComponent>

            <!-- <el-form-item label="大屏特效：">
                <el-row>
                    <span class="effect-name">{{pageData.screenEffect.name || '特效名称'}}</span>
                    <el-button type="text" @click="sfxLibraryVisibly = true">特效库</el-button>
                    <el-button type="text">清除</el-button>
                </el-row>
                <div class="detail-tip">如果为空，则默认显示整体设置中的特效</div>
            </el-form-item> -->
            <el-form-item label="抽奖功能类型：" class="effect-form-item">
                <div class="effect-list">
                    <div class="effect-item" v-for="(effect, index) in effectList" :key="index">
                        <el-radio
                            :label="effect.value"
                            v-model="pageData.effect.type"
                        >{{effect.name}}</el-radio>
                        <div class="effect-preview">
                            <el-button type="text">演示</el-button>
                        </div>
                    </div>
                </div>
            </el-form-item>
            <el-form-item label="抽奖风格：" class="effect-form-item">
                <div class="effect-list">
                    <div class="effect-item" v-for="(style, index) in styleList" :key="index">
                        <el-radio :label="style.value" v-model="pageData.style.type" @change="selectAwardStyle(style)">{{style.name}}</el-radio>
                        <div class="effect-preview">
                            <img :src="style.effectImg" :alt="style.name" />
                            <!-- <el-button type="text">演示</el-button> -->
                        </div>
                    </div>
                </div>
            </el-form-item>
            <el-form-item label="获奖特效：">
                <el-radio-group v-model="pageData.awardEffect">
                    <el-radio
                        :label="item.value"
                        v-for="(item, index) in awardEffects"
                        :key="index"
                    >{{item.name}}</el-radio>
                </el-radio-group>
            </el-form-item>
            <el-form-item label="大屏抽奖按钮：">
                <el-radio :label="1" v-model="pageData.isShowBtn">显示</el-radio>
                <el-radio :label="0" v-model="pageData.isShowBtn">隐藏</el-radio>
                <span class="detail-tip">无论隐藏还是显示，抽奖都可以使用互动小程序进行操作</span>
            </el-form-item>
            <el-form-item label="中奖名单：">
                <el-radio :label="1" v-model="pageData.isShowAwardList">显示</el-radio>
                <el-radio :label="0" v-model="pageData.isShowAwardList">隐藏</el-radio>
                <span class="detail-tip">获奖后，观众的互动小程序会有中奖通知</span>
            </el-form-item>
            <el-form-item label="奖品设置：" class="gift-setting">
                <el-button type="primary" @click="openDialog()">添加</el-button>
                <el-button type="danger" @click="deletePrizes">批量删除</el-button>
                <el-button type="text">帮助</el-button>
            </el-form-item>
            <div class="prize-list" v-if="prizeList && prizeList.length > 0">
                <el-card
                    v-for="(prize, prizeIndex) in prizeList"
                    :key="prizeIndex"
                    :class="{'selected': prizeSelection.indexOf(prizeIndex) > -1}"
                    @click.native="selectPrize(prizeIndex)"
                >
                    <el-row type="flex" justify="space-between" class="card-header">
                        <el-col :span="4">
                            <i class="el-icon-arrow-left" @click="sortPre(prizeIndex)"></i>
                        </el-col>
                        <el-col :span="16" class="prize-img">
                            <img :src="prize.prizeImgUrl" :alt="prize.prizeName" />
                        </el-col>
                        <el-col :span="4">
                            <i class="el-icon-arrow-right" @click="sortNext(prizeIndex)"></i>
                        </el-col>
                    </el-row>
                    <div class="card-content">
                        <div class="content-row">
                            <label class="content-label">奖项:</label>
                            <span class="content-info">{{prize.awardName}}</span>
                        </div>
                        <div class="content-row">
                            <label class="content-label">奖品:</label>
                            <span class="content-info">{{prize.prizeName}}</span>
                        </div>
                        <div class="content-row">
                            <label class="content-label">数量:</label>
                            <span class="content-info">{{prize.prizeNum}}</span>
                        </div>
                        <div class="content-row">
                            <label class="content-label">单位:</label>
                            <span class="content-info">{{prize.prizeUnit}}</span>
                        </div>
                    </div>
                    <div class="card-footer">
                        <el-button type="text" @click.stop="editPrize(prize, prizeIndex)">修改</el-button>
                        <el-button type="text" @click.stop="deletePrize(prize, prizeIndex)">删除</el-button>
                    </div>
                </el-card>
            </div>
        </el-form>
        <footerButtons @save="saveData">

        </footerButtons>
        <!-- <div class="detail-footer">
            <el-button type="danger">取消</el-button>
            <el-button type="primary" @click="saveData">保存</el-button>
        </div> -->

        <modal
            :visible="showPrizeDialog"
            :width="450"
            :top="100"
            @close="showPrizeDialog = false"
            class="data-modal"
            :title="isEditPrize ? '编辑奖品' : '添加奖品'"
        >
            <el-form :model="prizeObj" label-width="90px">
                <el-form-item label="奖项名称：">
                    <el-input v-model="prizeObj.awardName" placeholder="奖项名称"></el-input>
                </el-form-item>
                <el-form-item label="奖品名称：">
                    <el-input v-model="prizeObj.prizeName" placeholder="奖品名称"></el-input>
                </el-form-item>
                <el-form-item label="奖品数量：">
                    <el-input-number v-model="prizeObj.prizeNum" :min="1" label="奖品数量"></el-input-number>
                </el-form-item>
                <el-form-item label="奖品单位：">
                    <el-input v-model="prizeObj.prizeUnit"  placeholder="奖品单位"></el-input>
                </el-form-item>
                <el-form-item label="奖品图片：">
                    <el-button class="sign-style-btn" type="text" @click="materialLibraryVisibly = true">素材库</el-button>
                    <div class="img-preview">
                        <div class="img-box">
                            <img :src="prizeObj.prizeImgUrl || noData" />
                        </div>
                        <el-button type="text" @click="removePrizeImg">删除</el-button>
                    </div>
                </el-form-item>
                <el-form-item>
                    <el-button plain type="primary" @click="showPrizeDialog = false">取消</el-button>
                    <el-button type="primary" @click="commitPrize">确认</el-button>
                </el-form-item>
            </el-form>
        </modal>
        <el-dialog
            top="40px"
            :visible="picLibraryVisibly || materialLibraryVisibly"
            width="800px"
            title="图片库"
            @close="picLibraryVisibly = false,materialLibraryVisibly = false"
            append-to-body
            custom-class="library_dialog definedModal"
        >
            <imagesLibrary @selected="selectCurrentImg" @close="picLibraryVisibly = false,materialLibraryVisibly = false"></imagesLibrary>
        </el-dialog>
        <el-dialog
            top="40px"
            :visible="sfxLibraryVisibly"
            width="660px"
            title="特效库"
            @close="sfxLibraryVisibly = false"
            append-to-body
            custom-class="definedModal"
        >
            <specialLibrary @selected="selectCurrentSpx" @close="sfxLibraryVisibly = false"></specialLibrary>
        </el-dialog>
    </div>
</template>

<script>
import bgImage from '../../../../assets/imgs/fj.jpg';
import defaultBg from '../../../../assets/imgs/bg_2.png';
import noData from '../../../../assets/imgs/no_data/no_data.png';
import imagesLibrary from '../baseSetting/library/imagesLibrary';
import specialLibrary from '../baseSetting/library/specialLibrary';
import backgComponent from "@/pages/common/bgComponent"

import { configMerge } from '@/utils/pageConfig';
import { generateNumberID } from '@/utils/util';

const IMAGE_PREFIX = "https://www.office2.cn/staticft/images/awardimage/";

export default {
    name: 'prizeBaseSetting',
    components: {
        imagesLibrary,
        specialLibrary,
        backgComponent
    },
    props: {
        pageName: {
            type: String,
            default: '',
        },
        pageId: {},
    },
    data() {
        return {
            defaultBg: defaultBg,
            noData: noData,
            pageDefaultData:{
              css:{
                zIndex:1,
                width:"100%",
                height:"100%"
              }
            },
            pageData: {
                bgImage: "",
                d3Config:"",
                screenEffect: {
                    name: '',
                },

                // 抽奖功能类型
                effect: {
                    type: 'helix',
                },

                // 抽奖风格
                style: {
                    type: 1,
                },
                awardEffect: 0, // 获奖特效
                isShowBtn: 1, // 是否显示大屏抽奖按钮
                isShowAwardList: 1, // 是否显示中奖名单
            },
            effectList: [
                { name: '滚筒', value: "helix" },
                { name: '球形', value: "sphere" },
                // { name: '3D星空', value: 3 },
            ],
            styleList: [
                { 
                    name: '红金', 
                    effectImg: IMAGE_PREFIX + 'Red_gold/effectImg.png',
                    bg: IMAGE_PREFIX + 'Red_gold/bg.png',
                    left: IMAGE_PREFIX + 'Red_gold/left.png',
                    right: IMAGE_PREFIX + 'Red_gold/right.png',
                    value: 1 
                },
                { 
                    name: '科技蓝',
                    effectImg: IMAGE_PREFIX + 'Technology_Blue/effectImg.png',
                    bg: IMAGE_PREFIX + 'Technology_Blue/bg.png',
                    left: IMAGE_PREFIX + 'Technology_Blue/left.png',
                    right: IMAGE_PREFIX + 'Technology_Blue/right.png',
                    value: 2
                }
            ],
            awardEffects: [
                { name: '无', value: 0 },
                { name: '烟花', value: 1 },
                // { name: '礼炮', value: 2 },
                // { name: '撒钱', value: 3 },
            ],
            prizeList: [
                {
                    prizeImgUrl: defaultBg,
                    awardName: '一等奖',
                    prizeName: 'iphone XR Max',
                    prizeNum: 2,
                    prizeUnit: "部",

                },
                {
                    prizeImgUrl: defaultBg,
                    awardName: '二等奖',
                    prizeName: '红米 Red mi 6s',
                    prizeNum: 5,
                    prizeUnit: "部",
                },
            ],

            showPrizeDialog: false,
            isEditPrize: false,         // 是否编辑奖品
            prizeObj: {},
            currentEditIndex: null,
            prizeSelection: [],
            picLibraryVisibly: false,
            materialLibraryVisibly: false,  // 添加奖品素材库标识
            sfxLibraryVisibly: false,
            bgComponent:{},
            prizeComponent:{},
            bgComponentId:"",
            prizeComponentId:"",
        };
    },
    computed: {
        realPageId() {
            if ((this.pageId + '').indexOf('add') > -1) {
                return null;
            } else {
                return this.pageId;
            }
        },
    },

    created() {
      var {path} = this.$route;
      if((path+"").indexOf('add') < 0){
        this.getSetting();
      }
    },

    methods: {
        bgChange(data,url){
            this.pageData.bgImage = url;
            this.pageData.d3Config = data;
        },
        goTpshow() {
            const { name } = this.$route;
            if ((name + '').indexOf('add') != -1) {
                this.$confirm('当前场景页还未保存,请先保存。', {
                    confirmButtonText: '保存',
                    cancelButtonText: '取消',
                    type: 'warning',
                }).then(_ => {
                    this.saveData();
                }).catch(_ =>{

                });
            }else{
                this.saveData("goTpshow")
            }
        },
        // 图片库选择结果
        selectCurrentImg(data) {
            if (this.picLibraryVisibly) {
                this.pageData.bgImage = data.url;
            } else if (this.materialLibraryVisibly) {
                this.prizeObj.prizeImgUrl = data.url;
            }
        },
        // 特效库选择结果
        selectCurrentSpx(data) {},
        clearBg() {
            this.pageData.bgImage = null;
        },

        // 保存奖品设置
        saveData(from) {
            console.log(this.pageData);
            if (!this.pageName) {
                return this.$message({
                    message: '场景页名称不能为空',
                    type: 'warning',
                });
            } else if (this.prizeList.length === 0) {
                return this.$message({
                    message: '奖品不能为空',
                    type: 'warning',
                });
            }
            
            // 抽奖元素数据结构
            let prizeElement = {
                sceneId: this.$route.query.sceneId,
                pageId: this.pageId,
                id: this.signComponentId || generateNumberID(), //每一个element都有一个id
                type: 'prize', // 类型为prize,代表抽奖组件
                effect: this.pageData.effect, // 抽奖功能类型
                style: this.pageData.style,
                awardEffect: this.pageData.awardEffect,
                isShowBtn: this.pageData.isShowBtn, // 是否显示大屏抽奖按钮
                isShowAwardList: this.pageData.isShowAwardList, // 是否显示中奖名单
                prizeList: this.prizeList,  // 奖项数据
            };
            // 构造数据  初次保存的时候使用默认的样式，
            let elements = [
                configMerge(_.extend({}, (this.prizeComponentId ? this.prizeComponent : this.pageDefaultData), prizeElement))
            ];
            // 判断是否选择了背景图,选择了背景图则在elements中添加背景组件
            if (this.pageData.bgImage) {
              var bgConfig = {
                    sceneId: this.$route.query.sceneId,
                    pageId:this.pageId,
                    id: this.bgComponentId || generateNumberID(),
                    type: '3',
                    properties: {
                        imgSrc: this.pageData.bgImage,
                        d3Config:this.pageData.d3Config
                    },
                }
                elements.push(configMerge(_.extend({},this.bgComponent,bgConfig)));
            }

            let param = {
                sceneId: this.$route.query.sceneId,
                name: this.pageName,
                num: this.pageData.num || 1,
                elements: elements,
                pageType: 3, // 抽奖类型为3
                pageidBigint: this.realPageId,
                screenEffect: this.pageData.screenEffect,
                prizeList: this.prizeList,
            };

            console.log(param);
            this.$api.post(
                '/stScenepage/savePage',
                param,
                response => {
                    let pageId = response;
                    this.$bus.$emit('menuRefresh', this.$route.path, pageId);
                    this.$message({
                        message: '设置成功',
                        type: 'success',
                    });
                    // 高级编辑
                    if (from === 'goTpshow') {
                        var {origin} = window.location;
                        if(origin.indexOf("localhost") > -1){
                          origin = "http://127.0.0.1:8088"
                        }
                        this.$nextTick(() => {
                            let token = sessionStorage.getItem('token');
                            var url = `${ origin }/staticft/#/scene/create/${
                                this.$route.query.sceneId
                            }?pageId=${this.pageData.num || 1}&type=smartscreen&token=${token}`;
                            window.location.replace(url);
                        });
                    }
                },
                fal => {
                    this.$message.error(fal);
                }
            );
        },

        getSetting() {
            this.$api.post(
                '/stScenepage/scenePageView',
                {
                    sceneId: this.$route.query.sceneId,
                    pageidBigint: this.realPageId,
                },
                response => {
                    console.log(response);
                    let bgComponent = response.elements.filter(item => {
                            return item.type === '3';
                        })[0],
                        prizeComponent = response.elements.filter(item => {
                            return item.type === 'prize';
                        })[0];
                    
                    this.bgComponentId = bgComponent && bgComponent.id;
                    this.prizeComponentId = prizeComponent && prizeComponent.id;
                    // 向父级发送场景页名称
                    this.$emit(
                        'initData',
                        response.name,
                        response.enablePreset
                    );
                    if(prizeComponent){
                      this.pageData = {
                          num: response.num,
                          pageId: response.id,
                          screenEffect: response.screenEffect || {}, // 大屏特效
                          effect: prizeComponent.effect || {}, // 上屏效果
                          prizeList: response.prizeList,
                          effect: prizeComponent.effect, // 抽奖功能类型
                          style: prizeComponent.style,
                          awardEffect: prizeComponent.awardEffect,
                          isShowBtn: prizeComponent.isShowBtn, // 是否显示大屏抽奖按钮
                          isShowAwardList: prizeComponent.isShowAwardList, // 是否显示中奖名单
                      }
                    }
                    if(bgComponent){
                      this.pageData.bgImage = bgComponent.properties.imgSrc;
                      this.pageData.d3Config = bgComponent.properties.d3Config;
                    }
                    // this.$message({
                    //     message: '查询成功',
                    //     type: 'success',
                    // });
                },
                fal => {
                    this.$message.error(fal);
                }
            );
        },

        /**
         * 设置抽奖风格
         * 将2d背景改成抽奖风格默认的背景
         */
        selectAwardStyle(style) {
            _.extend(this.pageData.style, style);
            this.pageData.bgImage = style.bg;
            this.pageData.d3Config = JSON.stringify({
                is3D: false,
                type: '2d'
            });
        },

        // 修改奖品项
        editPrize(prize, index) {
            this.currentEditIndex = index;
            this.openDialog(JSON.parse(JSON.stringify(prize)));
        },

        // 删除奖品
        deletePrize(prize, index) {
            this.prizeList.splice(index, 1);
        },

        openDialog(prize) {
            this.showPrizeDialog = true;
            if (prize && prize.prizeName) {
                this.isEditPrize = true;
                this.prizeObj = prize;
            } else {
                this.prizeObj = {
                    prizeNum: 1,
                }
            }
        },

        removePrizeImg() {
            this.prizeObj.prizeImgUrl = null;
        },
        commitPrize() {
            console.log(this.prizeObj);
            let obj = this.prizeObj;
            if (!obj.awardName) {
                return this.$message({
                    type: 'warning',
                    message: '奖项不能为空',
                });
            } else if (!obj.prizeName) {
                return this.$message({
                    type: 'warning',
                    message: '奖品不能为空',
                });
                // } else if (!obj.prizeImgUrl) {
                //     return this.$message({
                //         type: "warning",
                //         message: "奖品图片不能为空"
                //     })
            }
            if (this.currentEditIndex !== null) {
                this.prizeList[this.currentEditIndex] = this.prizeObj;
                this.currentEditIndex = null;
            } else {
                this.prizeList.push(this.prizeObj);
            }
            this.showPrizeDialog = false;
        },

        sortPre(prizeIndex) {
            if (prizeIndex === 0) {
                return;
            } else {
                let tmp,
                    list = this.prizeList.slice(),
                    preIndex = prizeIndex - 1;
                tmp = list[preIndex];
                list[preIndex] = list[prizeIndex];
                list[prizeIndex] = tmp;
                this.prizeList = list;
            }
        },
        sortNext(prizeIndex) {
            if (prizeIndex === this.prizeList.length - 1) {
                return;
            } else {
                let tmp,
                    list = this.prizeList.slice(),
                    nextIndex = prizeIndex + 1;
                tmp = list[nextIndex];
                list[nextIndex] = list[prizeIndex];
                list[prizeIndex] = tmp;
                this.prizeList = list;
            }
        },

        selectPrize(index) {
            if (this.prizeSelection.indexOf(index) < 0) {
                this.prizeSelection.push(index);
            } else {
                this.prizeSelection = this.prizeSelection.filter(item => {
                    return item !== index;
                });
            }
        },
        deletePrizes() {
            if (this.prizeSelection.length > 0) {
                this.prizeList = this.prizeList.filter((item, index) => {
                    return this.prizeSelection.indexOf(index) < 0;
                });
                this.prizeSelection = [];
            }
        },
    },
};
</script>

<style lang="scss">
.prize-base-setting {
    padding-bottom: 50px;

    .el-button--text {
        padding-left: 20px;
        padding-right: 20px;

        &:hover span {
            text-decoration: underline;
        }
    }

    .align-left {
        text-align: left;
    }

    .align-right {
        text-align: right;
    }

    .detail-content {
        margin: 30px 0;

        .img-container {
            width: 160px;
            min-height: 80px;
            border: 1px solid #eee;
            display: inline-flex;
            justify-content: center;
            align-items: center;

            .bg-img {
                max-width: 160px;
            }

            span {
                color: #afafaf;
            }
        }

        .vertical-top {
            button {
                vertical-align: top;
            }
        }

        .detail-tip {
            font-size: 12px;
            color: #afafaf;
        }

        .effect-name {
            color: #373737;
        }

        .effect-form-item {
            .el-form-item__label {
                line-height: 77px;
            }
        }

        .effect-list {
            display: flex;
            flex-wrap: wrap;
            align-items: center;

            .effect-item {
                margin-right: 60px;
                margin-bottom: 30px;
                display: inline-flex;
                align-items: center;

                .el-radio {
                    width: 100px;
                    margin-right: 10px;
                }

                .effect-preview {
                    display: inline-flex;
                    width: 120px;
                    height: 80px;
                    border: 1px solid #ccc;
                    border-radius: 4px;
                    justify-content: center;
                    align-items: center;

                    img {
                        max-width: 100%;
                        max-height: 100%;
                    }
                }
            }
        }

        .prize-list {
            display: flex;
            align-items: center;
            justify-content: flex-start;
            flex-direction: row;
            flex-wrap: wrap;
            padding-left: 120px;

            .el-card {
                width: 200px;
                margin-right: 30px;
                margin-bottom: 30px;
                position: relative;
                overflow: visible;

                &.selected {
                    border: 1px solid #f56c6c;
                }

                .el-card__body {
                    width: 100%;
                    height: 100%;
                    padding: 10px;
                }
            }

            .card-header {
                height: 100px;
                clear: both;

                .prize-img {
                    max-height: 100%;
                    display: flex;
                    align-items: center;
                    justify-content: center;
                    img {
                        max-width: 100%;
                        max-height: 100px;
                    }
                }

                i {
                    font-size: 32px;
                    text-align: left;
                    cursor: pointer;

                    &.el-icon-arrow-right {
                        float: right;
                        text-align: right;
                    }

                    &:hover {
                        color: #1989fa;
                    }
                }
            }

            .card-content {
                padding: 0 10px;

                .content-row {
                    margin: 5px 0;

                    .content-label {
                        font-weight: normal;
                        font-size: 14px;
                    }

                    .content-info {
                        display: inline;
                        font-size: 14px;
                        word-break: break-all;
                    }
                }
            }

            .card-footer {
                text-align: center;

                .el-button {
                    padding: 9px 15px;
                }
            }
        }

        .gift-setting {
            .el-button {
                width: 90px;
            }
        }
    }
    .detail-footer {
        margin-top: 20px;
        text-align: center;
    }

    .data-modal {
        .img-preview {
            display: flex;
            margin: 10px 0;
            align-items: center;

            .img-box {
                height: 100px;
                width: 150px;
                text-align: center;
                border: 1px solid #eee;
                border-radius: 4px;

                img {
                    max-width: 100%;
                    max-height: 100%;
                }
            }
        }
    }
}
</style>

